<template>
  <div id="app">
    <h1>第八题</h1>
    <div>
      <span>姓名:</span>
      <input type="text" v-model="name1" />
    </div>
    <div>
      <span>年龄:</span>
      <input type="number" v-model="age1" />
    </div>
    <div>
      <span>性别:</span>
      <select v-model="gender1">
        <option value="男">男</option>
        <option value="女">女</option>
      </select>
    </div>
    <div>
      <button @click="add">添加/修改</button>
    </div>
    <div>
      <table
        border="1"
        cellpadding="10"
        cellspacing="0"
        v-show="list.length > 0"
      >
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
        <tr v-for="(item, index) in list" :key="index">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="del(index)">删除</button>
            <button @click="btn(index)">编辑</button>
          </td>
        </tr>
      </table>
    </div>
  </div>
</template>
<script>
export default {
  name: "PageG",
  data() {
    return {
      name1: "",
      age1: "0",
      gender1: "男",
      editIndex: null, // 保存正在编辑的对象的索引, 千万不能给0和0以上的值(默认上来就是编辑状态)
      list: [
        { id: 1, name: "张三", age: 18, gender: "女" },
        { id: 2, name: "李四", age: 18, gender: "女" },
        { id: 3, name: "王五", age: 18, gender: "女" },
      ],
    };
  },

  methods: {
    add() {
      if (!this.name1 || !this.age1) {
        alert("名字和年龄不能为空");
        return;
      }

      const obj = {
        name: this.name1,
        age: this.age1,
        gender: this.gender1,
      };

      if (this.editIndex !== null) {
        // 本次是要编辑更新

        this.$set(this.list, this.editIndex, obj);
        // 千万注意
        this.editIndex = null; // 更新后, 保证下次点击是新增
      } else {
        // 新增
        this.list.push(obj);
      }

      //   初始化
      this.name1 = this.age1 = "";
    },

    del(i) {
      this.list.splice(i, 1);
    },
  },
};
</script>